{% extends "teacher/base.html" %}

{% block title %}个人信息 - 期末成绩登记统计分析系统{% endblock %}

{% block styles %}
<style>
  .profile-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 20px;
  }

  .profile-header {
    background: white;
    border-radius: var(--border-radius);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    padding: 30px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 30px;
    position: relative;
  }

  .profile-avatar {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    background: var(--light-blue);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    overflow: hidden;
    cursor: pointer;
    transition: transform 0.3s ease;
  }

  .profile-avatar:hover {
    transform: scale(1.05);
  }

  .profile-avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .profile-avatar i {
    font-size: 60px;
    color: var(--primary-blue);
  }

  .profile-info {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    min-height: 120px;
  }

  .profile-title {
    font-size: 28px;
    color: var(--text-primary);
    margin: 0 0 10px 0;
  }

  .profile-subtitle {
    color: var(--text-secondary);
    margin: 0;
    font-size: 16px;
  }

  .profile-actions {
    position: absolute;
    bottom: 30px;
    right: 30px;
  }

  .edit-button {
    background: var(--primary-blue);
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: var(--border-radius);
    cursor: pointer;
    font-size: 14px;
    transition: all var(--transition-speed) ease;
    display: flex;
    align-items: center;
    gap: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .edit-button:hover {
    background: var(--accent-blue);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .profile-content {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
  }

  .profile-card {
    background: white;
    border-radius: var(--border-radius);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    padding: 25px;
  }

  .card-title {
    font-size: 18px;
    color: var(--text-primary);
    margin: 0 0 20px 0;
    padding-bottom: 10px;
    border-bottom: 2px solid var(--light-blue);
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .card-title i {
    color: var(--primary-blue);
  }

  .info-group {
    margin-bottom: 20px;
  }

  .info-label {
    font-weight: bold;
    color: var(--text-secondary);
    margin-bottom: 5px;
    font-size: 14px;
  }

  .info-value {
    color: var(--text-primary);
    font-size: 16px;
    padding: 8px 12px;
    background: var(--light-blue);
    border-radius: var(--border-radius);
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }

  .stat-card {
    background: var(--light-blue);
    padding: 20px;
    border-radius: var(--border-radius);
    text-align: center;
    transition: all var(--transition-speed) ease;
  }

  .stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  }

  .stat-value {
    font-size: 28px;
    font-weight: bold;
    color: var(--primary-blue);
    margin: 10px 0;
  }

  .stat-label {
    color: var(--text-secondary);
    font-size: 14px;
  }

  /* 模态框样式优化 */
  .modal {
    display: none;
    /* 默认隐藏 */
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
    align-items: center;
    justify-content: center;
  }

  .modal.show {
    display: flex;
    /* 显示时使用flex布局 */
  }

  .modal-content {
    background: white;
    max-width: 500px;
    width: 90%;
    border-radius: var(--border-radius);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    position: relative;
    animation: modalFadeIn 0.3s ease;
  }

  @keyframes modalFadeIn {
    from {
      opacity: 0;
      transform: translateY(-20px);
    }

    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  .modal-header {
    padding: 20px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .modal-header h3 {
    margin: 0;
    color: var(--text-primary);
    font-size: 20px;
  }

  .close {
    font-size: 24px;
    color: var(--text-secondary);
    cursor: pointer;
    transition: color var(--transition-speed) ease;
  }

  .close:hover {
    color: var(--text-primary);
  }

  .modal-body {
    padding: 20px;
  }

  .form-group {
    margin-bottom: 20px;
  }

  .form-group label {
    display: block;
    margin-bottom: 8px;
    color: var(--text-secondary);
    font-weight: bold;
  }

  .form-group input {
    width: 100%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: var(--border-radius);
    font-size: 14px;
  }

  .form-group input:focus {
    border-color: var(--primary-blue);
    outline: none;
    box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
  }

  .modal-footer {
    padding: 20px;
    border-top: 1px solid #eee;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  .btn {
    padding: 10px 20px;
    border-radius: var(--border-radius);
    cursor: pointer;
    font-size: 14px;
    transition: all var(--transition-speed) ease;
  }

  .btn-primary {
    background: var(--primary-blue);
    color: white;
    border: none;
  }

  .btn-primary:hover {
    background: var(--accent-blue);
  }

  .btn-secondary {
    background: #f8f9fa;
    color: var(--text-primary);
    border: 1px solid #ddd;
  }

  .btn-secondary:hover {
    background: #e9ecef;
  }

  /* 添加头像上传相关样式 */
  .avatar-upload-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 15px;
    padding: 15px;
    background: var(--light-blue);
    border-radius: var(--border-radius);
  }

  .avatar-preview {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
  }

  .avatar-preview img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .avatar-preview i {
    font-size: 60px;
    color: var(--primary-blue);
  }

  .avatar-upload-buttons {
    display: flex;
    gap: 10px;
  }

  .avatar-upload-buttons .btn {
    padding: 8px 15px;
    font-size: 14px;
  }
</style>
{% endblock %}

{% block content %}
<div class="profile-container">
  <div class="profile-header">
    <div class="profile-avatar" onclick="toggleAvatarUpload()">
      {% if registration and registration.avatar %}
      <img src="{{ registration.avatar }}" alt="头像" style="width: 100%; height: 100%; object-fit: cover;">
      <div style="display: none;">Debug: {{ registration.avatar }}</div>
      {% else %}
      <i class="fas fa-user"></i>
      {% endif %}
    </div>
    <div class="profile-info">
      <h1 class="profile-title">{{ current_user.name }}
        <i class="fas fa-mars" style="color: #1976d2; font-size: 24px; margin-left: 8px;"></i>
      </h1>
      <p class="profile-subtitle">{{ current_user.college.college_name }}</p>
    </div>
    <div class="profile-actions">
      <button class="edit-button" onclick="showEditModal()">
        <i class="fas fa-edit"></i>
        编辑信息
      </button>
    </div>
  </div>

  <div class="profile-content">
    <div class="profile-card">
      <h2 class="card-title">
        <i class="fas fa-id-card"></i>
        基本信息
      </h2>
      <div class="info-group">
        <div class="info-label">教师工号</div>
        <div class="info-value">{{ current_user.teacher_id }}</div>
      </div>
      <div class="info-group">
        <div class="info-label">所属学院</div>
        <div class="info-value">{{ current_user.college.college_name }}</div>
      </div>
      <div class="info-group">
        <div class="info-label">电子邮箱</div>
        <div class="info-value">{{ registration.email }}</div>
      </div>
      <div class="info-group">
        <div class="info-label">联系电话</div>
        <div class="info-value">{{ registration.phone }}</div>
      </div>
    </div>

    <div class="profile-card">
      <h2 class="card-title">
        <i class="fas fa-chart-bar"></i>
        工作统计
      </h2>
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-label">负责班级</div>
          <div class="stat-value">{{ stats.classes }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">教授课程</div>
          <div class="stat-value">{{ stats.courses }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">学生总数</div>
          <div class="stat-value">{{ stats.students }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">已录入成绩</div>
          <div class="stat-value">{{ stats.grades }}</div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- 编辑信息模态框 -->
<div id="editModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <h3>编辑个人信息</h3>
      <span class="close" onclick="closeModal()">&times;</span>
    </div>
    <div class="modal-body">
      <form id="editForm" onsubmit="updateProfile(event)">
        <!-- 添加头像上传部分 -->
        <div class="form-group">
          <label>头像</label>
          <div class="avatar-upload-container">
            <div class="avatar-preview">
              {% if registration and registration.avatar %}
              <img id="avatarPreview" src="{{ registration.avatar }}" alt="头像预览">
              {% else %}
              <i class="fas fa-user" id="avatarPreview"></i>
              {% endif %}
            </div>
            <div class="avatar-upload-buttons">
              <input type="file" id="avatarInput" accept="image/*" style="display: none"
                onchange="previewAvatar(event)">
              <button type="button" class="btn btn-secondary"
                onclick="document.getElementById('avatarInput').click()">选择图片</button>
              <button type="button" class="btn btn-primary" onclick="uploadAvatar()">上传头像</button>
            </div>
          </div>
        </div>
        <div class="form-group">
          <label for="email">电子邮箱</label>
          <input type="email" id="email" name="email" value="{{ registration.email }}" required>
        </div>
        <div class="form-group">
          <label for="phone">联系电话</label>
          <input type="tel" id="phone" name="phone" value="{{ registration.phone }}" required>
        </div>
        <div class="form-group">
          <label for="password">新密码（留空则不修改）</label>
          <input type="password" id="password" name="password">
        </div>
        <div class="form-group">
          <label for="confirm_password">确认新密码</label>
          <input type="password" id="confirm_password" name="confirm_password">
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
          <button type="submit" class="btn btn-primary">保存</button>
        </div>
      </form>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script>
  function showEditModal() {
    const modal = document.getElementById('editModal');
    modal.classList.add('show');
  }

  function closeModal() {
    const modal = document.getElementById('editModal');
    modal.classList.remove('show');
  }

  function updateProfile(event) {
    event.preventDefault();
    const form = event.target;
    const formData = new FormData(form);

    // 验证密码
    const password = formData.get('password');
    const confirmPassword = formData.get('confirm_password');
    if (password && password !== confirmPassword) {
      alert('两次输入的密码不一致');
      return;
    }

    // 发送更新请求
    fetch('/teacher/api/profile', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
      },
      body: JSON.stringify({
        email: formData.get('email'),
        phone: formData.get('phone'),
        password: password || undefined
      })
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          alert('个人信息更新成功');
          location.reload();
        } else {
          alert(data.message || '更新失败');
        }
      })
      .catch(error => {
        console.error('Error:', error);
        alert('更新失败，请稍后重试');
      });
  }

  // 点击模态框外部关闭
  window.onclick = function (event) {
    const modal = document.getElementById('editModal');
    if (event.target === modal) {
      closeModal();
    }
  }

  function previewAvatar(event) {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      const preview = document.getElementById('avatarPreview');

      reader.onload = function (e) {
        if (preview) {
          // 如果预览元素是图标，替换为图片
          if (preview.tagName === 'I') {
            const img = document.createElement('img');
            img.src = e.target.result;
            img.alt = '头像预览';
            preview.parentNode.replaceChild(img, preview);
          } else {
            preview.src = e.target.result;
          }
        }
      }
      reader.readAsDataURL(file);
    }
  }

  function uploadAvatar() {
    const fileInput = document.getElementById('avatarInput');
    const file = fileInput.files[0];
    if (!file) {
      alert('请先选择图片');
      return;
    }

    const formData = new FormData();
    formData.append('avatar', file);

    fetch('/api/upload-avatar', {
      method: 'POST',
      headers: {
        'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
      },
      body: formData
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          console.log('Upload success:', data);
          // 更新头像显示
          const avatarImg = document.querySelector('.profile-avatar img');
          if (avatarImg) {
            avatarImg.src = data.avatar_url + '?t=' + new Date().getTime(); // 添加时间戳防止缓存
          } else {
            const avatarDiv = document.querySelector('.profile-avatar');
            const newImg = document.createElement('img');
            newImg.src = data.avatar_url + '?t=' + new Date().getTime(); // 添加时间戳防止缓存
            newImg.alt = '头像';
            newImg.style.width = '100%';
            newImg.style.height = '100%';
            newImg.style.objectFit = 'cover';
            avatarDiv.innerHTML = '';
            avatarDiv.appendChild(newImg);
          }
          alert('头像上传成功');
          // 延迟刷新页面以确保数据库更新完成
          setTimeout(() => {
            window.location.reload();
          }, 1000);
        } else {
          console.error('Upload failed:', data);
          alert(data.message || '上传失败');
        }
      })
      .catch(error => {
        console.error('Upload error:', error);
        alert('上传失败，请稍后重试');
      });
  }
</script>
{% endblock %}